import { useQuery } from '@tanstack/react-query';
import { userApi } from '../api/user';

export function Leaderboard() {
  const { data: response } = useQuery({
    queryKey: ['leaderboard'],
    queryFn: () => userApi.getLeaderboard('points').then((res: any) => res.data),
  });

  const leaderboard = response?.data || response || [];

  const getRankColor = (rank: number) => {
    switch (rank) {
      case 1: return 'bg-yellow-400 text-yellow-900';
      case 2: return 'bg-gray-300 text-gray-900';
      case 3: return 'bg-orange-400 text-orange-900';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">排行榜</h1>
      
      <div className="bg-white rounded-lg shadow">
        <div className="divide-y">
          {leaderboard.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-gray-500">暂无排行榜数据</p>
            </div>
          ) : (
            leaderboard.map((entry: any) => (
              <div key={entry.userId} className="p-4 flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold ${getRankColor(entry.rank)}`}>
                    {entry.rank}
                  </div>
                  <div>
                    <h3 className="font-semibold">{entry.username}</h3>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-lg font-bold text-blue-600">{entry.value} 积分</p>
                  <p className="text-sm text-gray-600">{entry.coursesCompleted || 0} 门课程</p>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}